#!/bin/sh

VERSION_MJ="1"
VERSION_MN="0"
VERSION_RV="0000"
VERSION_AP=""
VERSION="${VERSION_MJ}.${VERSION_MN}${VERSION_AP}"

PATCHDIR="/usr/share/timidity"

# Below is the user's local patchset
HOME_TARGET="$HOME/.timidity/current"
TARGET="${HOME_TARGET}"

show_help() {
	echo "$0 ${VERSION}"
	echo "Usage: $0 [-g] -s PATCHSET"
	echo "  or:  $0 -r"
	echo "  or:  $0 [OPTION]"
	echo "Set the current timidity patch set to PATCHSET."
	echo
	echo "Mandatory arguments to long options are mandatory for short options too."
	echo "  -g                           Change the global patch set instead of the"
	echo "                               user's patch set"
	echo "  -r                           Change current user's patch set to current"
	echo "                               system patch set"
	echo "  -s [PATCHSET]                Change to patch set PATCHSET"
	echo "      --help     display this help and exit"
}

show_error() {
	
	echo "$0: bad or missing argument"
	echo "Try '$0 --help' for more information."
}

set_patch() {
	TARGET=$1
	PATCHSET=$2
	# If something borken, no go
	if [ ! -L ${TARGET} -a -e ${TARGET} ] || [ ! -d ${PATCHDIR}/${PATCHSET} ]; then
		if [ ! -L ${TARGET} -a -e ${TARGET} ]; then
			echo "  Error:  ${TARGET} exists and is not a symlink"
			return -1
		fi
		if [ ! -d ${PATCHDIR}/${PATCHSET} ]; then
			echo "  Error:  patch set ${PATCHSET} does not exist"
			echo "    Look in ${PATCHDIR}/ for patch sets"
			return -1
		fi
		echo "  Error:  Undefined error."
		return -1
	fi
	echo -n "    * Switching to ${PATCHSET} Timidity patch set..."
	rm -f ${TARGET} 2>/dev/null
	ln -s ${PATCHDIR}/${PATCHSET} ${TARGET} 2>/dev/null
	echo "      [  OK  ]"
	return 0
}

restore_patches() {
	TARGET=$1
	echo -n "    * Setting up local patch set to system global..."
	rm -f ${TARGET} 2>/dev/null
	ln -s ${PATCHDIR}/current ${TARGET}
	echo "      [  OK  ]"
}

##############
# Processing #
#############

# Make sure home directory is there
if [ ! -e ${HOME}/.timidity ]; then
	mkdir -p ${HOME}/.timidity
	restore_patches $TARGET
fi


################
# No arguments #
###############

if [ -z "$1" ]; then
	show_error
	exit 1
fi

#########################
# Actual processing loop#
########################
while [ -n "$1" ]; do
	case "$1" in
	-g)
		TARGET="/usr/share/timidity/current"
		;;
	-r)
		restore_patches ${HOME_TARGET}
		exit 0
		;;
	-s)
		PATCHSET="$2"
		shift
		;;
	--help)
		show_help
		exit 0
		;;
	*)
		show_error
		exit 1
		;;
	esac
	shift
done

set_patch $TARGET $PATCHSET
